<?php


namespace app\controller\api;

use app\model\Message;
use app\model\Uid;
use app\utils\AppRespUtil;
use GatewayClient\Gateway;
use app\BaseController;
use app\Request;

/**
 * 测试客服聊天-socket工具包
 * Class TestWebSocket
 * @package app\controller\api
 */
class TestWebSocket extends BaseController
{

    #测试发现 Gateway::sendToUid 出现丢包现象严重。
    #所以这里记录用户当前登录的客户端id，以便直接调用 Gateway::sendToClient 方法
    /**
     * @uid 解释这里uid泛指用户id或者设备id，用来唯一确定一个客户端用户或者设备。
     * @doc http://doc2.workerman.net/bind-uid.html
     *
     */

    /**
     * 自定义UID 绑定到 client_id【客户端id】
     * @param Request $request
     * @return string
     * @throws \app\exceptions\SystemException
     */
    public function bindClientId(Request $request)
    {
        $params = $request->only(['uid', 'client_id'], 'post');
        $this->validate(
            $params,
            [
                'uid|唯一标识UID' => 'require',
                'client_id|客户端id' => 'require',
            ]
        );
        $model = new Uid();
        $model->bindUidAndClientId($params);
        return AppRespUtil::success($params);
    }

    /**
     * 用户发送消息给客服
     * @param Request $request
     * @return string
     * @throws \app\exceptions\SystemException
     */
    public function sendMessageToCustomerService(Request $request)
    {
        $params = $request->only(['uid', 'message'], 'post');
        $this->validate(
            $params,
            [
                'uid|用户uid' => 'require',
                'message|消息内容' => 'require',
            ]
        );

        $json_str = json_encode($params, JSON_UNESCAPED_UNICODE);

        #发送消息到人工客服
        $model = new Uid();
        $client_id = $model->getClientIdByUid(serviceUid());
        if ($client_id && Gateway::isOnline($client_id)) {
            Gateway::sendToClient($client_id, $json_str); #如果对方在线，发送消息到指定客户端id处
        }

        #todo 其他操作可根据所需完善（例如：数据库保存消息记录等）
        $model = new Message();
        $model->insertMessageByUser($params);

        return AppRespUtil::success($params);
    }

    /**
     * 客服发送消息给用户
     * @param Request $request
     * @return string
     * @throws \app\exceptions\SystemException
     */
    public function replyMessageToUser(Request $request)
    {
        $params = $request->only(['to_uid', 'message'], 'post');
        $this->validate(
            $params,
            [
                'to_uid|用户uid' => 'require',
                'message|消息内容' => 'require',
            ]
        );
        $params['create_time'] = date('Y-m-d H:i:s',time());
        $json_str = json_encode($params, JSON_UNESCAPED_UNICODE);
        $model = new Uid();
        $client_id = $model->getClientIdByUid($params['to_uid']);
        if ($client_id && Gateway::isOnline($client_id)) {
            Gateway::sendToClient($client_id, $json_str); #如果对方在线，发送消息到指定客户端id处
        }

        $model = new Message();
        $model->insertMessageByCustomerService($params);

        return AppRespUtil::success($params);
    }

    /**
     * 得到聊天记录（指定uid）
     * @param Request $request
     * @return string
     * @throws \think\db\exception\DbException
     */
    public function getMessageListByUid(Request $request)
    {
        $params = $request->only(['uid', 'page', 'type'], 'post');
        $this->validate(
            $params,
            [
                'uid|用户uid' => 'require',
                'page|页码' => 'integer|gt:0',
                'type|类型' => 'require|in:u,s',
            ]
        );
        $params['page'] = (!isset($params['page'])) ? 1 : $params['page'];
        $model = new Message();
        return AppRespUtil::success($model->getMessageListByUid($params['uid'], (int)$params['page'],$params['type']));
    }

    /**
     *  得到消息列表（每组对话中，最新一条记录）
     * @param Request $request
     * @return string
     * @throws \think\db\exception\BindParamException
     */
    public function getLastMessage(Request $request)
    {
        $params = $request->only(['uid', 'page'], 'post');
        $this->validate(
            $params,
            [
                'page|页码' => 'integer|gt:0',
            ]
        );
        $params['page'] = (!isset($params['page'])) ? 1 : $params['page'];
        $limit = 15;
        $start = ($params['page'] - 1) * $limit;
        $model = new Message();
        $list = [];
        $total = $model->getMessageListTotal();
        if ($total) {
            $list = $model->getLastMessage($start, $limit);
            foreach ($list as &$val){
                $val['create_time'] = date('Y-m-d H:i',$val['create_time']);
                $val['img'] = '../img/tx'.mt_rand(1,4).'.png';//随机头像
            }
            array_multisort($list, SORT_DESC);
        }
        return AppRespUtil::success(['total' => $total, 'list' => $list]);
    }

    /**
     * 删除与指定用户的消息记录（所有消息）
     * @param Request $request
     * @return string
     */
    public function deleteMessage(Request $request)
    {
        $params = $request->only(['uid'], 'post');
        $this->validate(
            $params,
            [
                'uid|用户uid' => 'require',
            ]
        );
        $model = new Message();
        $model->deletedMessageByUid($params['uid']);
        return AppRespUtil::success();
    }

    /**
     * 查询未读消息数量（用户）
     * @param Request $request
     * @return string
     */
    public function getUnreadTotalByUid(Request $request)
    {
        $params = $request->only(['uid'], 'post');
        $this->validate(
            $params,
            [
                'uid|用户uid' => 'require',
            ]
        );
        return AppRespUtil::success(['total'=>1]);
    }
}
